<template>
    <div class="content">
        <div class="search-content" v-if="$attrs.showDateSearch">
            <span>开始日期</span>
            <el-date-picker
                v-model="calulateDate.startDate"
                align="right"
                placeholder="开始日期"
                :picker-options="traderDatePickerS"
                value-format="yyyyMMdd"
                format="yyyy-MM-dd"
                @change="startDateChange"
                size="mini"
                style="width: 160px"
            >
            </el-date-picker>
            <span>结束日期</span>
            <el-date-picker
                v-model="calulateDate.endDate"
                align="right"
                placeholder="结束日期"
                :picker-options="traderDatePickerE"
                value-format="yyyyMMdd"
                format="yyyy-MM-dd"
                size="mini"
                style="width: 160px"
            >
            </el-date-picker>
            <el-button size="mini" type="primary" @click="handleBtnSearch">查询</el-button>
        </div>
        <div class="chart-content">
            <p v-if="!$attrs.showDateSearch">
                {{ `${transToResultDetail.fundCode} ${transToResultDetail.fundName} ${transToResultDetail.firstOverrunDate}` }}
            </p>
            <p v-if="!$attrs.showDateSearch">{{ `"${transToResultDetail.entryName}"指标超标的主要因素为 ${transToResultDetail.overrunName}` }}</p>
            <p v-if="$attrs.showDateSearch">{{ transToResultDetail.entryName }}</p>
            <OverBranchFlowChart
                :searchParams="{
                    startDate: calulateDate.startDate,
                    endDate: calulateDate.endDate,
                    entryKey: transToResultDetail.entryKey,
                }"
                @branch-change="branchChange"
                :key="tableKey + 'branch'"
                :entryName="transToResultDetail.entryName"
                ref="chart"
                v-if="$attrs.isActive"
                :isFollow="$attrs.showDateSearch"
            />
        </div>
        <div class="table-content" :style="{ height: $attrs.showDateSearch ? 'calc(60vh - 120px)' : 'calc(60vh - 90px)' }">
            <RiskTableP
                :ref="'risk-table'"
                :tableConfig="tableConfig"
                :tableData="tableData"
                :column="tableColumns"
                v-loading="tableLoading"
                :min-width="'100px'"
                v-if="tableColumns.length > 0"
            >
            </RiskTableP>
        </div>
    </div>
</template>
<script lang="ts">
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { ColumnVO, PageVO, TableConfigVO } from '@/common/vo';
import moment from 'moment';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import API from '../api/over-reason-follow';
import DictionConstUtil from '@/utils/diction-const-util';
import OverBranchFlowChart from './over-branch-flow-chart.vue';
@Component({ name: 'OverReasonDetail', components: { RiskTableP, OverBranchFlowChart } })
export default class OverReasonDetail extends Vue {
    // 详情数据
    @Prop() transToResultDetail;
    realDirectionPojo: any = {};
    tableKey: number = -1;
    tableConfig: TableConfigVO = {
        rowKey: 'causeId',
    };
    tableLoading: boolean = false;
    tableData: any[] = [];
    a = [
        {
            attrValue: 56,
            balance: 43,
            calculateValue: 45,
            causeId: 895103258679529472,
            causeType: '1',
            detailId: 895103258679529472,
            fundCode: '2109',
            originalDirection: 'W',
            realDirection: 'W',
            stockCode: '000001 SS',
        },
        {
            amount: 657,
            attrValue: 435,
            balance: 97,
            causeId: 895103258679529472,
            confirmDate: 20210901,
            detailId: 895103258679529472,
            direction: 'P',
            fundCode: '2109',
            fundName: '高',
            settleDate: 20210909,
            tradeDate: 20210812,
        },
        {
            attrValue: 34,
            balance: 65,
            causeId: 895103258679529472,
            detailId: 895103258679529472,
            direction: 'D',
            stockCode: '000001 SS',
            subjectCode: 'GFH',
            subjectName: '546',
            voucherNo: '2',
        },
        {
            attrType: '3',
            attrValue: 464,
            calculateValue: 213,
            causeId: 895103258679529472,
            detailId: 895103258679529472,
            stockCode: '000001 SS',
        },
    ];
    tableColumns: ColumnVO[] = [];
    // 主动
    activeColumns: ColumnVO[] = [
        { field: 'fundCode', title: '产品代码', minWidth: 100 },
        { field: 'fundName', title: '产品名称', minWidth: 100 },
        { field: 'date', title: '日期', minWidth: 100 },
        { field: 'stockCode', title: '证券代码', minWidth: 100 },
        { field: 'stockName', title: '证券名称', minWidth: 100 },
        { field: 'realDirection', title: '交易方向', minWidth: 100, render: value => this.realDirectionPojo[value] },
        { field: 'amount', title: '数量', minWidth: 100 },
        { field: 'balance', title: '金额', minWidth: 100 },
        { field: 'calculateValue', title: '因子名称', minWidth: 100 },
        { field: 'attrValue', title: '归因影响值', minWidth: 100 },
    ];
    // 被动(申购、赎回)
    forceColumns: ColumnVO[] = [
        { field: 'fundName', title: '机构名称' },
        { field: 'date', title: '销售日期' },
        { field: 'confirmDate', title: '确认日期' },
        { field: 'settleDate', title: '交收日期' },
        { field: 'amount', title: '申购/赎回份额' },
        { field: 'balance', title: '申购/赎回金额' },
        { field: 'attrValue', title: '归因影响值' },
    ];
    // 市场波动：
    marketWave: ColumnVO[] = [
        { field: 'date', title: '日期' },
        { field: 'voucherNo', title: '凭证编号' },
        { field: 'subjectCode', title: '科目代码' },
        { field: 'subjectName', title: '科目名称' },
        { field: 'remark', title: '摘要' },
        {
            field: 'direction',
            title: '借贷',
            render: value => {
                return { C: '借', D: '贷' }[value];
            },
        },
        { field: 'balance', title: '金额' },
        { field: 'attrValue', title: '归因影响值' },
    ];
    // 证券属性（证券到期、 剩余期限变动、评级变动）
    stockParams: ColumnVO[] = [
        { field: 'date', title: '日期' },
        { field: 'stockCode', title: '证券代码' },
        { field: 'stockName', title: '证券名称' }, //
        { field: 'calculateValue', title: '因子名称' },
        { field: 'attrValue', title: '归因影响值' },
    ];

    columnTypeObj = {
        '101': this.activeColumns,
        '201': this.forceColumns,
        '202': this.marketWave,
        '203': this.stockParams,
    };

    paging: PageVO = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };
    private calulateDate = {
        startDate: '',
        endDate: '',
    };
    @Watch('transToResultDetail', { deep: true, immediate: true })
    changeDetail() {
        // 处理显示字段
        console.log(this.transToResultDetail, 'firstOverrunDate');
        // 取值字段依次为点击日期->超限区间->估值日期
        this.calulateDate.startDate = String(
            this.transToResultDetail.startDate || this.transToResultDetail.firstOverrunDate || this.transToResultDetail.tradeDate || ''
        );
        this.calulateDate.endDate = String(
            this.transToResultDetail.endDate || this.transToResultDetail.firstRestoreDate || this.transToResultDetail.tradeDate || ''
        );
        this.handleBtnSearch();
    }

    traderDatePickerS = {
        disabledDate: time => {
            const startDate = moment(String(this.transToResultDetail.firstOverrunDate)).format('yyyy-MM-DD');
            let minDate = Date.parse(startDate);
            const endDate = moment(String(this.transToResultDetail.firstRestoreDate)).format('yyyy-MM-DD');
            let maxDate = Date.parse(endDate);
            console.log(minDate, this.transToResultDetail.firstOverrunDate, 'this.transToResultDetail.firstOverrunDate');
            // 开始日期不能比调整为合规的日期大且要不小于超限第一天
            // let maxDate = new Date().getTime();
            return time.getTime() < minDate - 3600 * 1000 * 24 || time.getTime() > maxDate;
        },
    };

    traderDatePickerE = {
        disabledDate: time => {
            let minDate;
            let maxDate;
            if (this.calulateDate.startDate) {
                const startDate = moment(this.calulateDate.startDate).format('yyyy-MM-DD');
                minDate = Date.parse(startDate);
            } else {
                // 没有选定开始日期时,使用超限日期
                const startDate = moment(String(this.transToResultDetail.firstOverrunDate)).format('yyyy-MM-DD');
                minDate = Date.parse(startDate);
            }

            const endDate = moment(String(this.transToResultDetail.firstRestoreDate)).format('yyyy-MM-DD');
            maxDate = Date.parse(endDate);
            // 如果最大日期 比 今天 还大的话  就用今天
            if (maxDate > new Date().getTime()) {
                return time.getTime() > new Date().getTime() || time.getTime() < minDate - 3600 * 1000 * 24;
            } else {
                return time.getTime() > maxDate || time.getTime() < minDate - 3600 * 1000 * 24;
            }
        },
    };
    /**
     * 分支改变
     */
    branchChange(row) {
        console.log(row);
        this.tableColumns = this.columnTypeObj[row.columnType] || [];
        // 展示日期查询条件时，直接从图节点中获取数据
        if (this.$attrs.showDateSearch) {
            this.tableData = row.detailList;
        } else {
            this.tableLoading = true;
            return new Promise((resolve, reject) => {
                API.overReasonById({
                    serialNo: row.serialNo,
                    branchNo: row.branchNo,
                    ...this.calulateDate,
                    entryKey: this.transToResultDetail.entryKey,
                } as any)
                    .then((res: any) => {
                        this.tableData = res;
                        this.tableLoading = false;
                        resolve(res);
                    })
                    .catch(err => {
                        this.tableLoading = false;
                        reject(err);
                    });
            });
        }
    }

    async created() {
        this.realDirectionPojo = DictionConstUtil.ListToPojo(await DictionConstUtil.FNTradeDirection());
        let obj = this.activeColumns.find(item => item.field == 'realDirection');
        obj.render = value => this.realDirectionPojo[value];
    }

    // 计算开始日期改变
    private startDateChange(val): void {
        this.calulateDate.endDate = undefined;
    }

    handleBtnSearch() {
        // 重新渲染达到刷新效果---
        this.tableKey++;
        this.tableColumns = [];
        this.tableData = [];
    }
}
</script>
<style lang="scss" scoped>
.content {
    padding: 10px;
    height: calc(100vh - 47px);
    .search-content {
        & > span {
            margin: 0 10px;
            color: #333;
        }
        .el-button {
            margin-left: 10px;
        }
    }
    .chart-content {
        margin: 10px 0;
        height: 40vh;
        width: 100%;
        p {
            color: #333;
            text-align: center;
        }
    }
    .table-content {
        height: calc(100vh - 390px);
    }
}
</style>
